package org.automated.realestatemanager.dataanaliser;

import java.math.BigInteger;
import java.util.Set;

import org.apache.log4j.Logger;
import org.automated.realestatemanager.db.entity.Phone;
import org.automated.realestatemanager.db.entity.Publisher;
import org.automated.realestatemanager.db.services.PhoneService;
import org.automated.realestatemanager.db.services.ServiceFactory;
import org.automated.realestatemanager.db.util.HibernateUtility;

public class Analyzer {

	private static final Logger log = Logger.getLogger(Analyzer.class);

	@SuppressWarnings("static-access")
	public static Publisher getPhonesOwner(final Set<Phone> phones) {
		final PhoneService phoneService = ServiceFactory.getInstance()
				.getPhoneService();
		Publisher result = null;
		Publisher additionalPublisher = null;
		for (final Phone phone : phones) {
			if (phoneService.getByPhone(phone.getPhone()) != null) {

				final String request = "select publ.publisher_id as id "
						+ "from publishers publ left outer join "
						+ "publ_phones p_phon on publ.publisher_id=p_phon.publishers_publisher_id "
						+ "left outer join phones phs on p_phon.phones_phone_id=phs.phone_id "
						+ "where phs.phone=" + phone.getPhone();

				log.debug("Trying to find phone owner for phone " + phone
						+ "\n request " + request);

				Long id = null;
				try {
					id = ((BigInteger) HibernateUtility.getSession()
							.createSQLQuery(request).uniqueResult())
							.longValue();
				} catch (Exception ex) {
				}

				if (id != null) {
					if (result == null) {
						result = ServiceFactory.getInstance()
								.getPublisherService().get(id);
						log.debug("Owner found " + result);
					} else if (result != null) {
						additionalPublisher = ServiceFactory.getInstance()
								.getPublisherService().get(id);
						log.debug("Owner found " + result);
						if (result.getId() != additionalPublisher.getId()) {
							result = ServiceFactory
									.getInstance()
									.getPublisherService()
									.mergePuplishers(additionalPublisher,
											result);
						}
					}

				}

			} else {
				phoneService.create(phone);
				phones.add(phone);
			}
		}
		return result;
	}
}
